// 全局变量
let selectedFileId = null;
let selectedFileType = null;
let previewMode = 'dual'; // dual, single, overlay
let isShowingOverlay = false;

// DOM元素
const pdfUploadForm = document.getElementById('pdf-upload-form');
const pdfDropzone = document.getElementById('pdf-dropzone');
const pdfFileInput = document.getElementById('pdf-file-input');
const pdfBrowseButton = document.getElementById('pdf-browse-button');
const pdfUploadSubmit = document.getElementById('pdf-upload-submit');
const pdfUploadProgressContainer = document.getElementById('pdf-upload-progress-container');
const pdfUploadProgressBar = document.getElementById('pdf-upload-progress-bar');
const pdfUploadFilename = document.getElementById('pdf-upload-filename');
const pdfUploadPercentage = document.getElementById('pdf-upload-percentage');

const imageUploadForm = document.getElementById('image-upload-form');
const imageDropzone = document.getElementById('image-dropzone');
const imageFileInput = document.getElementById('image-file-input');
const imageBrowseButton = document.getElementById('image-browse-button');
const imageUploadSubmit = document.getElementById('image-upload-submit');
const imageUploadProgressContainer = document.getElementById('image-upload-progress-container');
const imageUploadProgressBar = document.getElementById('image-upload-progress-bar');
const imageUploadFilename = document.getElementById('image-upload-filename');
const imageUploadPercentage = document.getElementById('image-upload-percentage');

const filesContainer = document.getElementById('files-container');
const noFilesMessage = document.getElementById('no-files-message');
const searchFiles = document.getElementById('search-files');
const filterStatus = document.getElementById('filter-status');
const filterType = document.getElementById('filter-type');

const translationProgressModal = document.getElementById('translation-progress-modal');
const translationProgressBar = document.getElementById('translation-progress-bar');
const translationPercentage = document.getElementById('translation-percentage');
const translationFilename = document.getElementById('translation-filename');
const closeProgressModal = document.getElementById('close-progress-modal');
const cancelTranslation = document.getElementById('cancel-translation');

const previewSection = document.getElementById('preview-section');
const previewFilename = document.getElementById('preview-filename');
const closePreview = document.getElementById('close-preview');
const originalContent = document.getElementById('original-content');
const translationContent = document.getElementById('translation-content');

const modeDualBtn = document.getElementById('mode-dual');
const modeSingleBtn = document.getElementById('mode-single');
const modeOverlayBtn = document.getElementById('mode-overlay');

// 初始化事件监听器
function initEventListeners() {
    // PDF上传区域事件
    pdfDropzone.addEventListener('dragover', handleDragOver);
    pdfDropzone.addEventListener('dragleave', handleDragLeave);
    pdfDropzone.addEventListener('drop', handlePdfDrop);
    pdfBrowseButton.addEventListener('click', () => pdfFileInput.click());
    pdfFileInput.addEventListener('change', handlePdfFileSelect);
    pdfUploadForm.addEventListener('submit', handlePdfUpload);
    
    // 图片上传区域事件
    imageDropzone.addEventListener('dragover', handleDragOver);
    imageDropzone.addEventListener('dragleave', handleDragLeave);
    imageDropzone.addEventListener('drop', handleImageDrop);
    imageBrowseButton.addEventListener('click', () => imageFileInput.click());
    imageFileInput.addEventListener('change', handleImageFileSelect);
    imageUploadForm.addEventListener('submit', handleImageUpload);
    
    // 搜索和过滤事件
    searchFiles.addEventListener('input', filterFiles);
    filterStatus.addEventListener('change', filterFiles);
    filterType.addEventListener('change', filterFiles);
    
    // 预览模式切换
    modeDualBtn.addEventListener('click', () => switchPreviewMode('dual'));
    modeSingleBtn.addEventListener('click', () => switchPreviewMode('single'));
    modeOverlayBtn.addEventListener('click', () => switchPreviewMode('overlay'));
    
    // 关闭预览
    closePreview.addEventListener('click', () => {
        previewSection.classList.add('hidden');
    });
    
    // 关闭进度模态框
    closeProgressModal.addEventListener('click', () => {
        translationProgressModal.classList.add('hidden');
    });
    
    // 取消翻译
    cancelTranslation.addEventListener('click', () => {
        // 这里应该发送取消请求到后端
        translationProgressModal.classList.add('hidden');
    });
}

// 处理拖拽事件
function handleDragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    this.classList.add('border-primary');
    this.classList.add('bg-primary/5');
}

function handleDragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    this.classList.remove('border-primary');
    this.classList.remove('bg-primary/5');
}

// 处理PDF文件上传
function handlePdfDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    this.classList.remove('border-primary');
    this.classList.remove('bg-primary/5');
    
    const files = e.dataTransfer.files;
    if (files.length > 0) {
        pdfFileInput.files = files;
    }
}

function handlePdfFileSelect(e) {
    const files = e.target.files;
    if (files.length > 0) {
        pdfDropzone.classList.remove('border-gray-300');
        pdfDropzone.classList.add('border-green-500');
        
        const fileNames = Array.from(files).map(file => file.name).join(', ');
        pdfDropzone.innerHTML = `
            <i class="fa fa-file-pdf-o text-5xl text-green-500 mb-4"></i>
            <p class="text-lg text-gray-600 mb-2">已选择 ${files.length} 个文件</p>
            <p class="text-sm text-gray-500 truncate">${fileNames}</p>
            <button type="button" id="pdf-browse-button" class="mt-4 bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-custom">
                <i class="fa fa-folder-open mr-2"></i>选择其他文件
            </button>
        `;
        
        // 重新绑定按钮事件
        document.getElementById('pdf-browse-button').addEventListener('click', () => pdfFileInput.click());
    }
}

// 处理图片文件上传
function handleImageDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    this.classList.remove('border-primary');
    this.classList.remove('bg-primary/5');
    
    const files = e.dataTransfer.files;
    if (files.length > 0) {
        imageFileInput.files = files;
    }
}

function handleImageFileSelect(e) {
    const files = e.target.files;
    if (files.length > 0) {
        imageDropzone.classList.remove('border-gray-300');
        imageDropzone.classList.add('border-green-500');
        
        const fileNames = Array.from(files).map(file => file.name).join(', ');
        imageDropzone.innerHTML = `
            <i class="fa fa-image text-5xl text-green-500 mb-4"></i>
            <p class="text-lg text-gray-600 mb-2">已选择 ${files.length} 个文件</p>
            <p class="text-sm text-gray-500 truncate">${fileNames}</p>
            <button type="button" id="image-browse-button" class="mt-4 bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-custom">
                <i class="fa fa-folder-open mr-2"></i>选择其他文件
            </button>
        `;
        
        // 重新绑定按钮事件
        document.getElementById('image-browse-button').addEventListener('click', () => imageFileInput.click());
    }
}

// 处理PDF上传
function handlePdfUpload(e) {
    e.preventDefault();
    
    const files = pdfFileInput.files;
    if (files.length === 0) {
        alert('请选择PDF文件');
        return;
    }
    
    const serviceProvider = document.getElementById('pdf-translation-service').value;
    const apiKey = document.getElementById('api-key').value;
    
    uploadFiles(files, 'pdf', serviceProvider, apiKey);
}

// 处理图片上传
function handleImageUpload(e) {
    e.preventDefault();
    
    const files = imageFileInput.files;
    if (files.length === 0) {
        alert('请选择图片文件');
        return;
    }
    
    const serviceProvider = document.getElementById('image-translation-service').value;
    const apiKey = document.getElementById('api-key').value;
    
    uploadFiles(files, 'image', serviceProvider, apiKey);
}

// 上传文件
function uploadFiles(files, fileType, serviceProvider, apiKey) {
    // 显示进度条容器
    if (fileType === 'pdf') {
        pdfUploadProgressContainer.classList.remove('hidden');
        pdfUploadProgressBar.style.width = '0%';
        pdfUploadPercentage.textContent = '0%';
    } else {
        imageUploadProgressContainer.classList.remove('hidden');
        imageUploadProgressBar.style.width = '0%';
        imageUploadPercentage.textContent = '0%';
    }
    
    Array.from(files).forEach(file => {
        // 检查文件类型
        const fileExt = file.name.split('.').pop().toLowerCase();
        if (fileType === 'pdf' && fileExt !== 'pdf') {
            alert('请选择PDF文件');
            return;
        }
        
        if (fileType === 'image' && !['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(fileExt)) {
            alert('请选择图片文件 (JPG, PNG, GIF, BMP)');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', file);
        formData.append('service_provider', serviceProvider);
        formData.append('api_key', apiKey);
        
        // 更新进度条显示
        if (fileType === 'pdf') {
            pdfUploadFilename.textContent = file.name;
        } else {
            imageUploadFilename.textContent = file.name;
        }
        
        // 发送文件到服务器
        fetch('/upload_and_translate', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                // 显示翻译进度模态框
                translationProgressModal.classList.remove('hidden');
                translationFilename.textContent = file.name;
                
                // 定期检查翻译进度
                checkTranslationStatus(data.id);
                
                // 重置上传区域
                if (fileType === 'pdf') {
                    pdfFileInput.value = '';
                    pdfDropzone.innerHTML = `
                        <i class="fa fa-file-pdf-o text-5xl text-gray-400 mb-4"></i>
                        <p class="text-lg text-gray-600 mb-2">拖拽PDF文件到此处，或点击选择文件</p>
                        <p class="text-sm text-gray-500">支持的格式：PDF (最大100MB)</p>
                        <input type="file" id="pdf-file-input" class="hidden" accept=".pdf" multiple>
                        <button type="button" id="pdf-browse-button" class="mt-4 bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-custom">
                            <i class="fa fa-folder-open mr-2"></i>选择文件
                        </button>
                    `;
                    pdfDropzone.classList.remove('border-green-500');
                    pdfDropzone.classList.add('border-gray-300');
                    
                    // 重新绑定按钮事件
                    document.getElementById('pdf-browse-button').addEventListener('click', () => pdfFileInput.click());
                } else {
                    imageFileInput.value = '';
                    imageDropzone.innerHTML = `